package cn.edu.zut.sunday.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class MD5Utils {

    public static String getMD5(String str) {
        StringBuilder sb = new StringBuilder("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes(StandardCharsets.UTF_8));
            dealVal(sb, md);
        } catch (NoSuchAlgorithmException e) {
            log.error("val:{} NoSuchAlgorithmException: {}", str, e.getMessage());
        }

        return sb.toString();
    }

    public static String getMD5(File file) {
        StringBuilder sb = new StringBuilder("");
        try (FileInputStream fis = new FileInputStream(file)) {
            // 读取数据
            byte[]        buffer = new byte[8192];
            int           len    = 0;
            MessageDigest md     = MessageDigest.getInstance("MD5");
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            // 处理字符
            dealVal(sb, md);
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException: {}", e.getMessage());
        } catch (FileNotFoundException e) {
            log.error("FileNotFoundException: {}", e.getMessage());
        } catch (IOException e) {
            log.error("IOException: {}", e.getMessage());
        }

        return sb.toString();
    }

    private static void dealVal(StringBuilder sb, MessageDigest md) {
        byte[] b = md.digest();
        int    d;
        for (byte value : b) {
            d = value;
            if (d < 0) {
                d = value & 0xff;
            }
            if (d < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(d));
        }
    }
}
